package com.sg.file.transform.provider.queue;

import com.sg.file.transform.api.dto.TransformReqeust;
import com.sg.file.transform.provider.center.TransformCenter;
import com.sg.file.transform.provider.center.TransformCode;
import com.sg.file.transform.provider.center.TransformCodeFactory;

import java.util.concurrent.LinkedTransferQueue;

/**
 * 转换队列处理类，用于延时转换任务处理pub，单例
 * Created by asus on 2018/7/20.
 */
public class TransformQueueProcessor {

    private final static LinkedTransferQueue<TransformReqeust> linkedTransferQueue = new LinkedTransferQueue<>();

    private final static TransformQueueProcessor transformQueueProcessor = new TransformQueueProcessor();

    //正在转换中，用于标识队列是否已经在处理中
    private static boolean transcoding = false;

    private TransformQueueProcessor(){

    }

    public static TransformQueueProcessor getInstance(){
        return  transformQueueProcessor;
    }

    /**
     * 将任务插入队列中
     * @param transformReqeust
     * @return
     */
    public synchronized boolean enqueue(TransformReqeust transformReqeust){
        if(transformReqeust==null){
            return false;
        }
        boolean flag = linkedTransferQueue.add(transformReqeust);
        if(flag&&linkedTransferQueue.size()>0&&!transcoding){
            transcoding =true;
        }
        return flag;
    }

    /**
     * 转化任务队列中的全换请求任务
     */
    public void transformTaskQueue(TransformCodeFactory transformCodeFactory){
        while(linkedTransferQueue.size()>0){
            TransformReqeust transformReqeust = linkedTransferQueue.poll();
            //执行转化
            TransformCenter.doTransform(transformReqeust);
        }
    }
    //将转换标识释放
    public synchronized void release(){
        transcoding = true;
    }
}
